<?php
// 应用公共文件
/**
 * 模型内统一数据返回
 * @param $code
 * @param string $msg
 * @param array $data
 * @return array
 */
if (!function_exists('dataReturn')) {

    function dataReturn($code, $msg = 'success', $data = []) {

        return ['code' => $code, 'data' => $data, 'msg' => $msg];
    }
}

/**
 * 统一返回json数据
 * @param $code
 * @param string $msg
 * @param array $data
 * @return \think\response\Json
 */
if (!function_exists('jsonReturn')) {

    function jsonReturn($code, $msg = 'success', $data = []) {

        return json(['code' => $code, 'data' => $data, 'msg' => $msg]);
    }
}

/**
 * 统一分页返回
 * @param $list
 * @return array
 */
if (!function_exists('pageReturn')) {

    function pageReturn($list) {
        if (0 == $list['code']) {
            return ['code' => 0, 'msg' => 'success', 'data' => [
                'total' => $list['data']->total(),
                'rows' => $list['data']->all()
            ]];
        }

        return ['code' => 0, 'msg' => 'success', [
            'total' => 0,
            'rows' => []
        ]];
    }
}

/**
 * 解析token中简短的用户信息
 * @param $token
 * @return array
 */
function getUserSimpleInfo($token) {

    try {

        $token = (new \Lcobucci\JWT\Parser())->parse($token);
    }catch (\Exception $e) {

        return dataReturn(-1, $e->getMessage());
    }

    $data = new \Lcobucci\JWT\ValidationData();

    $data->setIssuer($token->getClaim('iss'));
    $data->setAudience($token->getClaim('aud'));
    $data->setId($token->getClaim('jti'));

    if(!$token->validate($data)) {
        return dataReturn(-2, 'token validate');
    }

    return dataReturn(0, '', [
        'id' => $token->getClaim('id'),
        'name' => $token->getClaim('name'),
        'roleId' => $token->getClaim('roleId'),
        'avatar' => $token->getClaim('avatar'),
    ]);
}

/**
 * 从头部获取token
 * @return bool|string
 */
function getHeaderToken() {

    $header = request()->header();
    return substr($header['authorization'], 7);
}

/**
 * 生成密码
 * @param $password
 * @param $salt
 * @return string
 */
function makePassword($password, $salt) {

    return md5(md5($password . $salt));
}

/**
 * 生成菜单树
 * @param $data
 * @param $pid
 * @return array
 */
function makeMenuTree($data, $pid = 'node_pid') {

    $res = [];
    $tree = [];

    // 整理数组
    foreach ($data as $key => $vo) {

        $res[$vo['id']] = $vo;
        //$res[$vo['id']]['children'] = [];
    }
    unset($data);

    // 查询子孙
    foreach ($res as $key => $vo) {
        if($vo[$pid] != 0){
            $res[$vo[$pid]]['children'][] = &$res[$key];
        }
    }

    // 去除杂质
    foreach ($res as $key => $vo) {
        if(isset($vo[$pid]) && $vo[$pid] == 0){
            $tree[] = $vo;
        }
    }
    unset($res);

    return $tree;
}

/**
 *生成菜单节点
 * @param $data
 * @param string $pid
 * @return array
 */
function makeMenuTreeV2($data, $pid = 'node_pid') {

    $res = [];
    $tree = [];

    // 整理数组
    foreach ($data as $key => $vo) {

        $res[$vo['id']] = $vo;
        $res[$vo['id']]['children'] = [];
    }
    unset($data);

    // 查询子孙
    foreach ($res as $key => $vo) {
        if($vo[$pid] != 0){
            $res[$vo[$pid]]['children'][] = &$res[$key];
        }
    }

    // 去除杂质
    foreach ($res as $key => $vo) {
        if(isset($vo[$pid]) && $vo[$pid] == 0){
            $tree[] = $vo;
        }
    }
    unset($res);

    return $tree;
}

/**
 * 获取全部的节点数据
 * @return array
 */
function getNodeData() {
    try {

        $nodeModel = new \app\model\Node();
        $nodeInfo = $nodeModel->getAllNode();

        if ($nodeInfo['code'] != 0) {
            return ['code' => -1 , 'data' => [], 'msg' => $nodeInfo['msg']];
        }

        $tree = makeMenuTree($nodeInfo['data']->toArray());

        return ['code' => 0 , 'data' => $tree, 'msg' => $nodeInfo['msg']];

    } catch (\Exception $e) {

        return ['code' => -2 , 'data' => [], 'msg' => $e->getMessage()];
    }
}

/**
 * 递归遍历部门树，放入对应的用户
 * @param $deptTree
 * @param $dept2User
 * @return array
 */
function putUserIntoDept($deptTree, $dept2User)
{
    $deptUsers = [];
    foreach ($deptTree as $key => $vo) {
        $deptUsers[$key] = [
            'value' => $vo['value'],
            'label' => $vo['label']
        ];

        if (isset($vo['children']) && !empty($vo['children'])) {
            $childDeptUser = putUserIntoDept($vo['children'], $dept2User);
            foreach ($childDeptUser as $k => $v) {
                $deptUsers[$key]['children'][] = $v;
            }
        }

        if (isset($dept2User[$vo['value']])) {
            foreach ($dept2User[$vo['value']] as $k => $v) {
                $deptUsers[$key]['children'][] = $v;
            }
        }
    }



    return $deptUsers;
}

/**
 * 生成表
 * @param $table
 * @return string
 */
function makeTable($table)
{
    return config('database.connections.mysql.prefix') . $table;
}
